package com.motorhome.api.common.interceptor;

import com.motorhome.api.common.statics.ApiStatics;
import com.motorhome.base.cache.MemcachedCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author: John
 */
public class ApiSecureInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(ApiSecureInterceptor.class);

    @Autowired
    private MemcachedCache cache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        //Cross-Origin Resource Sharing
        response.addHeader("Access-Control-Allow-Origin", "*");

        //Request parameters
        Map<String, String[]> paramsMap = request.getParameterMap();
        for (String key : paramsMap.keySet()) {
            request.setAttribute(key, paramsMap.get(key)[0]);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            modelAndView.addObject("baseFileUrl", ApiStatics.baseFileUrl);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }
}
